<template>
	<view class="user-page">
		<view class="head box-pading" @click="handleShowPop">
			<image v-if="token" :src="userInfo.backgroundImg" class="user-bg" mode="aspectFill"></image>
			<u-navbar :safeAreaInsetTop="true" bgColor="transparent" rightIcon="more-dot-fill" :fixed="false" :autoBack="false" :placeholder="true">
				<view class="navbar-left flex-no-horizontal" @tap.stop="leftClick" slot="left">
					<image src="../../static/shezhi.png" mode=""></image>
				</view>
				<view class="navbar-right flex-no-horizontal" slot="right">
					<view class="flex-no-horizontal" @tap.stop="rightClick(1)" style="position: relative; margin-right: 30rpx">
						<image src="/static/search/addUser.png" mode=""></image>
					</view>
					<view class="flex-no-horizontal" @tap.stop="rightClick(2)" style="position: relative">
						<u-badge
							numberType="overflow"
							max="99"
							:value="message.commentNum + message.followers + message.likeNum"
							:absolute="true"
							:offset="[-2, -6]"
							style="z-index: 1"
						>
						</u-badge>
						<image src="../../static/xiaoxi.png" mode=""></image>
					</view>
				</view>
				<view slot="center"></view>
			</u-navbar>

			<basicInformation
				:userInfo="userInfo"
				:userRelation="userRelation"
				@handleClick="handleClick"
				@handleSign="handleSign"
				class="u-z-index"
				v-if="token"
				ref="basicInfor"
				:isShowSignTip="isShowSignTip"
			></basicInformation>
			<view class="not-login-info u-z-index" v-else>
				<u--image src="../../static/img/avatar.png" width="100" height="100" shape="circle" class="m-b-20"> </u--image>
				<u-button shape="circle" color="#000000" style="width: 166px" @click="login">立即登录/注册</u-button>
				<text class="f-xs m-t-10 grey">登录后获取更多精彩内容</text>
			</view>
		</view>

		<view class="main box-pading" v-if="token">
			<!-- 我的订单 -->
			<view class="orders">
				<view class="orders-wrap flex-no-horizontal">
					<view class="title"> 我的订单 </view>
					<view class="icon" @click="toMyOrder()">
						<u-icon name="arrow-right" color="#000" size="25"></u-icon>
					</view>
				</view>
				<view class="order_opera flex-no-horizontal">
					<view class="order_type" @click="toMyOrder(1)">
						<view class="icon">
							<image src="@/static/market/buy.png" mode="widthFix"></image>
						</view>
						购买
					</view>
					<view class="order_type" @click="toMyOrder(2)">
						<view class="icon">
							<image src="@/static/market/sell.png" mode="widthFix"></image>
						</view>
						寄售
					</view>
					<view class="order_type" @click="toMyOrder(3)">
						<view class="icon">
							<image src="@/static/market/want.png" mode="widthFix"></image>
						</view>
						求购
					</view>
					<view class="order_type" @click="toMyOrder(4)">
						<view class="icon">
							<image src="@/static/market/bid.png" mode="widthFix"></image>
						</view>
						出价
					</view>
				</view>
			</view>
			<!-- 藏品信息 -->
			<collection v-show="shopOpenType == '1'" ref="collections" class="my-collection" :style="{ 'z-index': cssZindex }"></collection>
		</view>
		<view class="main box-pading not-login-down" v-else>
			<view class="f-large bold m-b-20">我的藏品</view>
			<view class="not-login-down-empty">
				<u--image src="../../static/empty/index-empty.png" width="209" height="154"></u--image>
				<text class="f-xs grey">请登录后查看藏品</text>
			</view>
		</view>
		<!-- 显示我得到的赠品 -->
		<u-popup :show="isShowGetGift" mode="center" @close="confirmAccept" round="10">
			<view class="get-collection border-box">
				<view class="m-b-10 text-center collection-title">恭喜您</view>
				<view class="text-center m-b-20 f-15">
					收到朋友赠送的藏品
					<!-- {{isHandleAccept ? '珍惜' : ''}} -->
				</view>
				<template v-if="accept">
					<u--image v-if="isHandleAccept" :src="accept.image" width="520rpx" height="520rpx" radius="3" class="m-b-30"> </u--image>
					<u--image v-else :src="accept.nft_img_url" width="520rpx" height="520rpx" radius="3" class="m-b-30"> </u--image>
					<view class="flex-no-horizontal get-item f-xs m-b-10">
						<view>赠送人：</view>
						<view v-if="isHandleAccept">{{ accept.form_user_username }}</view>
						<view v-else>{{ accept.form_name }}</view>
					</view>
					<view class="flex-no-horizontal get-item f-xs m-b-10 hash">
						<view class="white f-xs">赠送人地址：</view>
						<view class="white f-xs hash-right text-right" v-if="isHandleAccept">{{ accept.address }}</view>
						<view class="white f-xs hash-right text-right" v-else>{{ accept.form_address }}</view>
					</view>
					<view class="flex-no-horizontal get-item f-xs m-b-10">
						<view>赠送时间：</view>
						<view v-if="isHandleAccept">{{ accept.update_time }}</view>
						<view v-else>{{ accept.transfer_time }}</view>
					</view>
					<!-- <view class="flex-no-horizontal get-item f-xs m-b-10 hash" v-if="isHandleAccept">
						<view class="white f-xs">交易哈希：</view>
						<view class="white f-xs hash-right text-right">{{accept.tx_id}}</view>
					</view> -->
					<view class="flex-no-horizontal get-item f-xs hash">
						<view class="white f-xs">赠送藏品信息：</view>
						<view class="white f-xs hash-right text-right" v-if="isHandleAccept">{{ accept.title || accept.nft_name }}</view>
						<view class="white f-xs hash-right text-right" v-else>{{ accept.nft_title || accept.nft_name }}</view>
					</view>
					<view class="flex-no-horizontal get-item f-xs m-b-15 hash">
						<view class="white f-xs"></view>
						<view class="white f-xs hash-right text-right" v-if="isHandleAccept">{{ accept.number }}</view>
						<view class="white f-xs hash-right text-right" v-else>#{{ accept.token_id }}</view>
					</view>
				</template>
				<view class="get-btn text-center" @click="confirmAccept"> 收下藏品 </view>
			</view>
		</u-popup>
		<!-- 是否更换封面图 -->
		<currency-popup
			:popupShow="isShowChangeBg"
			title="更换封面"
			subhead="是否要更换封面？"
			@popupHide="isShowChangeBg = false"
			@popupConfirm="changeBg"
		></currency-popup>
		<!-- 申诉弹窗 -->
		<complaint
			:PopupShow="appealPopupShow"
			:articleId="dynamicId"
			:isTypeComplaint="false"
			@closeComplaint="appealPopupShow = false"
			@confirm="confirmAppeal"
			title="请输入申述理由"
			confirmBgColor="#000000"
		>
		</complaint>
		<animation-user ref="animationUser"></animation-user>
		<!-- 是否获得勋章 -->
		<get-medal :show="false"></get-medal>
		<medal-detail :show="false"></medal-detail>

		<!-- 更多选择弹窗 -->
		<moreSelect
			:showOverlay="ifShowSelect"
			isInHome
			:record="selectData.record"
			:offsetY="selectData.offsetY"
			@hideOverlay="moreSelectHide"
			@specificFunc="selectSpecificFunc"
		></moreSelect>

		<!-- 签到弹窗 -->
		<sign-in :show="isShowSign" @close="isShowSign = false" :signInData="signInData"></sign-in>
	</view>
</template>
<script>
import { acceptNft, confirmAcceptApi, receiveBox, transferBoxDetails, saveCidApi, signInApi, special_effects_check } from "../../api/collection.js";
import { ifLoginFun } from "../../utility/weChatLogin.js";
import { updataUserBg, isShowPopup } from "../../api/user.js";
import { userDynamicHistoryListApi, userInfoApi, userRelationApi, unreadMessageAllApi } from "../../api/index.js";
import { appealApi } from "@/api/examine.js";
import basicInformation from "./common/userBasicInfo.vue";
import collection from "./common/collection.vue";
import dynamic from "../community/common/dynamic.vue";
import currencyPopup from "../community/common/currencyPopup.vue";
import complaint from "../community/common/complaint.vue";
import SignIn from "./common/SignIn.vue";
import { shop_open } from "../../api/apiH5.js";
import { getQiniuData, uploadQiniu } from "../../utility/upload.js";
import { mapState, mapMutations } from "vuex";
import ZPagingMixin from "@/uni_modules/z-paging/components/z-paging/js/z-paging-mixin";
import dynamicMore from "../../common/mixin/dynamic.js";
import getMedal from "./common/getMedal.vue";
import medalDetail from "./common/medalDetail.vue";
import animationUser from "./common/animationUserUpdate.vue";
import moreSelect from "../community/common/dynamicMore.vue";
export default {
	components: {
		collection,
		dynamic,
		basicInformation,
		currencyPopup,
		getMedal,
		medalDetail,
		complaint,
		moreSelect,
		SignIn,
		animationUser,
	},
	mixins: [ZPagingMixin, dynamicMore],
	data() {
		return {
			shopOpenType: "", //是否展示 IOS审核隐藏
			isShowSignTip: false,
			isShowSign: false,
			signInData: {},
			dataList: [],
			userInfo: {
				avatar: "",
				blockchainAddr: "",
				code: "",
				sex: 1,
				sign: "",
				userId: "",
				username: "",
			},
			userRelation: {
				follower: 0,
				following: 0,
				likeNum: 0,
			},
			screening: [
				{
					active: true,
					name: "按时间",
				},
				{
					active: false,
					name: "按点赞",
				},
				{
					active: false,
					name: "按评论",
				},
			],
			dynamicSort: 0, //动态排序方式 0时间 1点赞最多，2评论最多
			message: {
				commentNum: 0,
				followers: 0,
				likeNum: 0,
			},
			empty: {
				emptyText: "您还没发布过动态，先去发布一条动态吧～",
				emptyImgUrl: "/static/empty/index-empty.png",
				emptyImgStyle: {
					width: "228px",
					height: "172px",
				},
				emptyToReleaseStyle: {
					padding: "10px 30px",
					backgroundColor: "#4ABC5A",
					borderRadius: "20px",
					color: "#FFFFFF",
					border: "none",
				},
				emptyBtnText: "去发布",
			},
			isShowChangeBg: false,
			isShowGetGift: false, //判断是否显示转增弹框
			accept: null,
			acceptId: 0,
			appealPopupShow: false,
			dynamicId: 0,
			cssZindex: 1,
			selectData: {
				record: {},
				offsetY: 0,
			},
			ifShowSelect: false,
			isShowHyperblockChain: false,
			isHandleAccept: false, //是否有百度链藏品
			isHyperblockChain: false, //是否有超块链藏品
			searchUpdateShows: false, //是否好友互关展示动画
			animationNmae: "", //动画名称
		};
	},
	computed: {
		...mapState({
			token: (state) => state.userToken,
			updateAnimation: (state) => state.updateAnimation,
		}),
	},
	// onReady() {
	// 	// #ifdef APP-PLUS
	// 	if (this.token) {
	// 		this.handleAccept()
	// 	}
	// 	// #endif
	// 	uni.$on('close', () => {
	//
	// onLoad() {
	// 	this.isShowSign = true
	// },
	onLoad() {
		if (this.token) {
			this.onUpdateAnimation();
		}
	},
	mounted() {
		const query = uni.createSelectorQuery().in(this);
		query
			.select("#textFont")
			.boundingClientRect((data) => {
				console.log(44444, data);
				// this.elData = data;
				// this.$forceUpdate()
			})
			.exec();
	},
	onShow() {
		if (this.token) {
			this.getUserInfo();
			this.getMessage();
			this.getUserRelationship();
			this.handleAccept();
			this.hyperblockChain();
			this.onShopOpenType();
			// uni.$on()
			// this.saveCid()
			this.$nextTick(() => {
				this.$refs.collections.closeBox();
			});
		}
		// this.getAttestErr()
		uni.$once("detailBlack", (data) => {
			this.$refs.paging.reload();
		});
	},
	methods: {
		...mapMutations(["setUserInfo", "setUpdateAnimation"]),

		toMyOrder(type) {
			if (!type) {
				uni.navigateTo({
					url: "/pages/market/order",
				});
			} else {
				uni.navigateTo({
					url: "/pages/market/order?type=" + type,
				});
			}
		},

		//是否展示
		async onShopOpenType() {
			try {
				const res = await shop_open();
				this.shopOpenType = res.data.data;
			} catch (e) {
				console.log(e);
			}
		},
		//动画引导
		async onUpdateAnimation() {
			try {
				const res = await special_effects_check({
					distinguish: "userPage",
				});
				let data = res.data.data;
				data.forEach((item, index) => {
					switch (item) {
						case "search_friends_guide":
							this.animationNmae = item;
							this.$refs.animationUser.onOpen("userPage", this.animationNmae);
							break;
						default:
							break;
					}
				});
			} catch (e) {
				console.log(e);
			}
		},
		//自定义导航左侧点击事件
		leftClick() {
			if (!ifLoginFun()) return;
			this.$nextTick(() => {
				uni.navigateTo({
					url: "/pages/user/set",
				});
			});
		},
		//自定义导航右侧点击事件
		rightClick(type) {
			if (!ifLoginFun()) return;
			if (type == 1) {
				uni.navigateTo({
					url: "./search/searchIndex",
				});
			} else {
				uni.navigateTo({
					url: "../community/message",
				});
			}
		},
		toUserInfo() {
			if (!ifLoginFun()) return;
			uni.navigateTo({
				url: "./userInfo",
			});
		},
		handleClick() {
			if (!ifLoginFun()) return;
			uni.navigateTo({
				url: "./userInfo",
			});
		},
		//动态排序点击
		dynamicSortClick(index) {
			if (!ifLoginFun()) return;
			this.dynamicSort = index;
			this.$refs.paging.reload();
		},
		login() {
			uni.navigateTo({
				url: "./login",
			});
		},
		//空状态，去发布
		toRelease(e) {
			e(false);
			uni.navigateTo({
				url: "../community/releaseDynamic",
			});
		},
		//下拉刷新,上拉加载
		async queryList(pageNo, pageSize) {
			if (!this.token) {
				this.$refs.paging.complete(false);
				return;
			}
			try {
				const res = await userDynamicHistoryListApi({
					orderModel: this.dynamicSort,
					mid: this.userId,
					pageNum: pageNo,
					pageSize,
				});

				this.$refs.paging.complete(res.data || []);
			} catch (e) {
				//TODO handle the exception
				this.$refs.paging.complete(false);
			}
		},
		openSubNvue() {
			const subNVue = uni.getSubNVueById("getFreebies");
			subNVue.show("fade-in", 300, () => {
				uni.$emit("show", this.acceptData);
			});
		},
		//百度链赠送藏品
		async handleAccept() {
			try {
				const res = await acceptNft();
				if (res.data.data) {
					this.acceptId = res.data.data.id;
					res.data.data.update_time = uni.$u.timeFormat(res.data.data.update_time, "yyyy-mm-dd hh:MM");
					this.accept = res.data.data;
					this.isShowGetGift = true;
					this.isHandleAccept = true;
					// this.openSubNvue()
				}
			} catch (e) {
				console.log(e);
			}
		},
		//超块链赠送藏品
		async hyperblockChain() {
			try {
				const res = await transferBoxDetails();
				if (res.data.id) {
					this.acceptId = res.data.id;
					res.data.transfer_time = uni.$u.timeFormat(res.data.transfer_time, "yyyy-mm-dd hh:MM");
					this.accept = res.data;
					this.isShowGetGift = true;
					this.isHyperblockChain = true;
					// this.openSubNvue()
				}
			} catch (e) {
				console.log(e);
			}
		},
		//手下藏品
		async confirmAccept() {
			try {
				let res;
				//百度链藏品
				if (this.isHandleAccept) {
					res = await confirmAcceptApi({
						shard_id: this.acceptId,
					});
					//超块链藏品
				} else if (this.isHyperblockChain) {
					res = await receiveBox({
						boxId: this.acceptId,
					});
				}
				this.isShowGetGift = false;
				this.isHyperblockChain = false;
				this.isHandleAccept = false;
				this.hyperblockChain();
				this.handleAccept();
			} catch (e) {
				this.isShowGetGift = false;
				this.isHandleAccept = false;
				this.isHyperblockChain = false;
				console.log(e);
			}
		},
		async handleSign() {
			try {
				const res = await signInApi();
				this.signInData = {
					continue: res.data.continuous,
					stone: res.data.store,
					tomorrowStone: res.data.tomorrow_store,
				};
				this.isShowSign = true;
				this.getUserInfo();
			} catch (e) {
				console.log(e);
				uni.showToast({
					title: e.data || e.message,
					icon: "none",
				});
				//TODO handle the exception
			}
		},
		async getUserInfo() {
			try {
				const res = await userInfoApi({});
				this.userInfo = res.data;
				this.setUserInfo(res.data);
				if (!this.userInfo.isSign) {
					setTimeout(() => {
						this.isShowSignTip = true;
					}, 1000);
				} else {
					this.isShowSignTip = false;
				}
			} catch (e) {
				console.log(e);
			}
		},
		async getMessage() {
			try {
				if (this.$store.state.userToken !== "") {
					//消息
					const message = await unreadMessageAllApi();
					this.message = message.data;
				}
			} catch (e) {
				//TODO handle the exception
				console.log(e);
			}
		},
		async getUserRelationship() {
			try {
				//用户关系信息
				const userRelationRes = await userRelationApi();
				this.userRelation = userRelationRes.data;
			} catch (e) {
				console.log(e);
				//TODO handle the exception
			}
		},
		//刷新数据
		refreshList() {
			this.$refs.paging.reload();
		},
		handleShowPop() {
			if (!this.token) return;
			this.isShowChangeBg = true;
		},
		changeBg() {
			this.isShowChangeBg = false;
			uni.chooseImage({
				count: 1,
				success: async (response) => {
					console.log();
					uni.showLoading({
						title: "图片上传中...",
					});
					try {
						const res = await getQiniuData();
						const url = await uploadQiniu(res.data, response.tempFiles[0]);
						await updataUserBg({
							backgroundImg: res.data.domain + url.key,
						});
						this.getUserInfo();
						uni.hideLoading();
					} catch (e) {
						console.log(e);
						uni.hideLoading();
						uni.showToast({
							title: e.data || e.message,
							icon: "none",
						});
					}
				},
				fail: () => {
					uni.showToast({
						title: "选择图片失败",
						icon: "none",
					});
				},
			});
		},
		showAppealPopup(data) {
			this.dynamicId = data.dynamicId;
			this.appealPopupShow = true;
		},
		// 确认申诉
		async confirmAppeal(reason) {
			try {
				const res = await appealApi({
					ctype: 1,
					content: reason,
					cid: this.dynamicId,
				});
				uni.showToast({
					title: "申诉成功，等待管理员审核",
					icon: "none",
				});
				this.appealPopupShow = false;
			} catch (e) {
				console.log(e);
				uni.showToast({
					title: e.data || e.message,
					icon: "none",
				});
			}
		},
		// saveCid() {
		// 	if (uni.getStorageSync('cid')) return
		// 	// #ifdef APP-PLUS
		// 	const cid = plus.push.getClientInfo().clientid
		// 	saveCidApi({cid}).then(res => uni.setStorageSync('cid', cid)).catch(err => console.log(err))
		// 	// #endif
		// }
	},
};
</script>

<style lang="scss" scoped>
::v-deep .zp-paging-container-content {
	z-index: auto !important;
}

// ::v-deep.u-popup__content {
// 	background-color: transparent !important;
// }
::v-deep .zp-container {
	z-index: 0 !important;
}

.user-page {
	min-height: 100%;

	.grey {
		color: #929292;
	}

	.not-login-info {
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		margin: 40rpx 0 80rpx;
	}

	.not-login-down {
		padding-top: 40rpx;

		.not-login-down-empty {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			margin-bottom: 100rpx;
		}
	}

	::v-deep .box {
		padding-top: 63rpx;
	}

	::v-deep .u-navbar__content__left,
	::v-deep .u-navbar__content__right {
		padding: 0;
	}

	.head {
		padding-bottom: 30rpx;
		background: linear-gradient(0, #f1f7fc, #e3e8eb);
		position: relative;

		// z-index: 20;
		.user-bg {
			// height: 1000rpx!important;
			position: absolute;
			width: 100%;
			height: 100%;
			left: 0;
			top: 0;
		}

		.u-z-index {
			position: relative;
			z-index: 2;
		}

		.navbar-left {
			image {
				width: 48rpx;
				height: 48rpx;
			}
		}

		.navbar-right {
			justify-content: center;

			view {
				image {
					display: inline-block;
					width: 48rpx;
					height: 48rpx;
				}
			}
		}
	}

	.main {
		border-radius: 40rpx 40rpx 0 0;
		background-color: white;
		margin-top: -40rpx;
		position: relative;

		.orders {
			// margin-bottom: 50rpx;
			padding-top: 48rpx;
			border-radius: 40rpx 40rpx 0 0;

			.orders-wrap {
				justify-content: space-between;

				.title {
					font-size: $uni-font-size-xlg;
					color: $uni-color-black;
					font-weight: bold;
				}
			}

			.order_opera {
				justify-content: space-between;
				margin-top: 20rpx;
				.order_type {
					flex: 1;
					text-align: center;

					.icon {
						width: 60rpx;
						height: 60rpx;
						margin: 8rpx auto;
						image {
							width: 100%;
						}
					}
				}
			}
		}

		.my-collection {
			background-color: #ffffff;
			position: relative;
			z-index: 1;
		}
	}

	.get-collection {
		background: #191919;
		color: white;
		border-radius: 10rpx;
		padding: 60rpx 40rpx;
		width: 600rpx;

		.collection-title {
			font-size: 20px;
		}

		.get-item {
			justify-content: space-between;
		}

		.hash {
			align-items: flex-start;

			.hash-right {
				width: 65%;
				word-break: break-all;
			}
		}

		.get-btn {
			background: #fde6c1;
			border-radius: 39rpx;
			color: #000000;
			font-size: 17px;
			padding: 16rpx 0;
			margin: auto;
			width: 334rpx;
		}
	}
}
</style>
